import { defineStore } from 'pinia'
import router, { Page404Route } from '@/plugins/router'
import $menus from '@/views/menus'
import { getMenus, Menu } from '@/api'
import type { RouteLocationNormalized } from 'vue-router'

interface Tag {
  name: string
  router: string
  routeName?: string
  fix?: boolean
  icon?: string
}
const homeTag: Tag = {
  name: '工作台',
  router: '/',
  routeName: 'Home',
  icon: 'icon-gongzuotai',
  fix: true
}

const starsStr = localStorage.getItem('stars')
const stars = starsStr ? JSON.parse(starsStr) : []
export default defineStore('menu', {
  state: () => ({
    menus: [] as Menu[],
    tags: [] as Tag[],
    fixedTags: [homeTag] as Tag[],
    stars: stars as string[]
  }),
  getters: {
    menuMap() {
      const map = new Map()
      this.menus.forEach(item => {
        map.set(item.url, item)
        if(item.list && item.list.length) {
          item.list.forEach(child => {
            map.set(child.url, child)
          })
        }
      })
      return map
    },
    starSet() {
      return new Set(this.stars)
    },
    allStarMenus() {
      return this.stars.map(item => this.menuMap.get(item)).filter(i => i)
    },
    allTags() {
      return [...this.fixedTags, ...this.tags]
    }
  },
  actions: {
    // 加载路由
    async init() {
      await this.refresh()
      router.removeRoute('PageLoading')
      router.addRoute(Page404Route)
    },
    async refresh() {
      const menus = await getMenus()
      this.menus = menus
      $menus.update(router, this.menus)
    },

    addRoute(route: RouteLocationNormalized) {
      const page = $menus.getLoadedPage(route.name as string)
      if (route.name === 'User') {
        this.addTag({ name: '我的资料', router: route.fullPath, routeName: route.name })
        return
      }
      if (!page) return
      this.addTag({ name: page.tag, router: route.fullPath, routeName: route.name })
    },
    addTag(tag: Tag) {
      if (!this.tags.some(item => item.router === tag.router)) {
        this.tags.push(tag)
      }
    },
    removeTag(tag: Tag) {
      const index = this.tags.findIndex(item => item.router === tag.router)
      if (index !== -1) {
        this.tags.splice(index, 1)
      }
    },
    clearTags() {
      this.tags = []
    },
    fixStar(star) {
      const index = this.stars.indexOf(star)
      if (index !== -1) {
        this.stars.splice(index, 1)
      } else {
        this.stars.push(star)
      }
      localStorage.setItem('stars', JSON.stringify(this.stars))
    }
  }
})